package com.jamal2362.apktool.task;

import android.content.Context;
import brut.util.OS;
import java.io.File;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.fragment.files.Refreshable;
import com.jamal2362.apktool.util.FileUtils;
import com.jamal2362.apktool.util.Settings;
import com.jamal2362.apktool.util.Zipper;

public class ExtractSplit extends AbstractTask {
	private Context context;
	private String name;
	private File outDir;
	private long time;

	public ExtractSplit(Context ctx, String name, Refreshable refresh) {
		super(ctx, refresh);
		this.context = ctx;
		this.name = name;
		this.time = System.currentTimeMillis();
	}

	@Override
	protected int getTitle() {
		return R.string.extract;
	}

	@Override
	protected boolean process(File f) {
		info(R.string.extraction, f.getAbsolutePath());
		String dir = Settings.output_directory;
		if (dir == null) {
			warning(R.string.output_directory_not_set);
			return false;
		}
		try {
			File d =  new File(dir);
			if (!d.exists() && !d.mkdirs()) {
				warning(R.string.output_directory_not_extsts, dir);
				return false;
			}
			if (!d.isDirectory()) {
				warning(R.string.not_directory, dir);
				return false;
			}
			outDir = new File(dir + "/ExtractSplit_" + time);
			if (!outDir.exists())
				outDir.mkdir();
			File out = new File(outDir, f.getName());
			return FileUtils.copyFiles(f, out);
		} catch (Exception e) {
			warning(R.string.errorf, e.getMessage());
			return false;
		}
	}

	@Override
	protected Boolean doInBackground(File[] p1) {
		boolean success = super.doInBackground(p1);
		if (success) {
			Zipper.zip(outDir.listFiles(), outDir.getParent() + "/" + name + ".apks");
			setResult(outDir.getParentFile());
			OS.rmdir(outDir);
		}
		return success;
	}

	@Override
	protected boolean shouldShowFinishDialog() {
		return true;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
	}
}
